import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * @program: learn_01
 * @description: 使用 异常
 * @author: Windlinxy
 * @create: 2022-04-06 15:40
 **/
public class UsingException {
    /**
     * throws关键字 声明一个会抛出异常的方法
     */
    public static void throwsTest() throws Exception {
        System.out.println("我使用throws");
    }

    /**
     * 调用带有异常声明的方法1：同样抛出去
     */
    public static void usingThrows01() throws Exception {
        throwsTest();
    }

    /**
     * 调用带有异常声明的方法2：进行一个处理
     */
    public static void usingThrows02() {
        try {
            throwsTest();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 自定义异常
     */
    public static void throwTest() throws MyException {
        throw new MyException("抛出异常");
    }

    /**
     * finally关闭资源
     */
    private static void readFile(String filePath) throws MyException {
        File file = new File(filePath);
        String result;
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            while((result = reader.readLine())!=null) {
                System.out.println(result);
            }
        } catch (IOException e) {
            System.out.println("readFile method catch block.");
            MyException ex = new MyException("read file failed.");
            ex.initCause(e);
            throw ex;
        } finally {
            System.out.println("readFile method finally block.");
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String finallyTest() {
        try {
            System.out.println("try");
            throw new Exception("异常了");
//            return "try返回";
        } catch (Exception e) {
            System.out.println("catch");
            e.printStackTrace();
            //finally
            return "catch返回";
        } finally {
            System.out.println("finally");
        }
    }

    public static void main(String[] args) {
//        1.throws关键字
////        try {
//            usingThrows01();
////        } catch (Exception e) {
////            e.printStackTrace();
////        }
//        usingThrows02();

//        System.out.println(finallyTest());

        // 2.throw关键字
        try {
            throwTest();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        System.out.println(finallyTest());

//        readFile("D:\\code cor\\project\\JAVA\\learn_01\\learn_Exception\\src\\WhyException.java");

    }
}
